import { type MockMethod } from 'vite-plugin-mock'

// 模拟用户数据
const users = [
  { id: '1', username: 'admin', password: 'admin123', email: 'admin@example.com', role: 'admin' },
  { id: '2', username: 'user1', password: 'user123', email: 'user1@example.com', role: 'user' },
  { id: '3', username: 'user2', password: 'user123', email: 'user2@example.com', role: 'user' }
]

const mock: MockMethod[] = [
  // 登录接口
  {
    url: '/api/auth/login',
    method: 'post',
    response: ({ body }) => {
      const { username, password } = body
      const user = users.find(u => u.username === username && u.password === password)
      if (user) {
        return {
          code: 200,
          message: '登录成功',
          data: {
            token: `token_${user.id}`,
            userInfo: {
              id: user.id,
              username: user.username,
              email: user.email,
              role: user.role
            }
          }
        }
      }
      return {
        code: 401,
        message: '用户名或密码错误'
      }
    }
  },

  // 登出接口
  {
    url: '/api/auth/logout',
    method: 'post',
    response: () => {
      return {
        code: 200,
        message: '登出成功'
      }
    }
  },

  // 获取用户信息接口
  {
    url: '/api/user/info',
    method: 'get',
    response: (req) => {
      const token = req.headers.authorization?.split(' ')[1]
      if (!token) {
        return {
          code: 401,
          message: '未授权'
        }
      }
      const userId = token.split('_')[1]
      const user = users.find(u => u.id === userId)
      if (user) {
        return {
          code: 200,
          message: '获取成功',
          data: {
            id: user.id,
            username: user.username,
            email: user.email,
            role: user.role
          }
        }
      }
      return {
        code: 404,
        message: '用户不存在'
      }
    }
  },

  // 获取用户列表接口
  {
    url: '/api/user/list',
    method: 'get',
    response: (req) => {
      const { page = 1, pageSize = 10, keyword = '' } = req.query
      const filteredUsers = users.filter(user =>
        user.username.includes(keyword) || user.email.includes(keyword)
      )
      const paginatedUsers = filteredUsers.slice(
        (Number(page) - 1) * Number(pageSize),
        Number(page) * Number(pageSize)
      )
      return {
        code: 200,
        message: '获取成功',
        data: {
          list: paginatedUsers,
          total: filteredUsers.length,
          page: Number(page),
          pageSize: Number(pageSize)
        }
      }
    }
  },

  // 创建用户接口
  {
    url: '/api/user',
    method: 'post',
    response: ({ body }) => {
      const { username, password, email, role } = body
      const newId = String(Number(users[users.length - 1].id) + 1)
      const newUser = { id: newId, username, password, email, role }
      users.push(newUser)
      return {
        code: 200,
        message: '创建成功',
        data: newUser
      }
    }
  },

]

export default mock